package com.example.studentcourse.config;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Properties;

public class CodeGenerator {
    public static void main(String[] args) {
        try {
            // 从配置文件中读取数据库连接信息
            Properties props = new Properties();
            Resource resource = new ClassPathResource("application.properties");
            props.load(resource.getInputStream());

            String url = props.getProperty("spring.datasource.url");
            String username = props.getProperty("spring.datasource.username");
            String password = props.getProperty("spring.datasource.password");

            // 检查输出目录是否存在且可写
            Path outputDir = Paths.get(props.getProperty("generator.outputDir", "src/main/java"));
            if (!Files.exists(outputDir)) {
                Files.createDirectories(outputDir);
            }
            if (!Files.isWritable(outputDir)) {
                throw new IOException("Output directory is not writable: " + outputDir);
            }

            FastAutoGenerator.create(url, username, password)
                    .globalConfig(builder -> {
                        builder.author(props.getProperty("generator.author", "your-name"))
                                .outputDir(outputDir.toString());
                    })
                    .packageConfig(builder -> {
                        builder.parent("com.example.studentcourse")
                                .pathInfo(Collections.singletonMap(OutputFile.mapper,
                                        props.getProperty("generator.mapperXmlPath", "src/main/resources/mapper")));
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude("student", "course", "student_course")
                                .entityBuilder().enableLombok()
                                .controllerBuilder().enableRestStyle();
                    })
                    .templateEngine(new VelocityTemplateEngine())
                    .execute();

        } catch (IOException e) {
            System.err.println("Error occurred during code generation: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
